import React from "react";
import { useEffect } from "react";
import { Button, Toast } from "antd-mobile";
interface Props {
  target: string;
  way?: string;
  handler: () => void;
}

const HOC =
  ({ target, way = "click", handler = () => {} }: Props) =>
  (Component: any) =>
  (props: any) => {
    useEffect(() => {
      const res = document.querySelector(target);
      res?.addEventListener(way, handler);
      return () => {
        res?.removeEventListener(way, handler);
      };
    }, []);

    return <Component {...props} />;
  };
// 子组件
const Child = () => {
  return (
    <div>
      <Button>赋能按钮</Button>
    </div>
  );
};

const Child1 = () => {
  return (
    <div
      id="id"
      style={{ marginTop: 10, background: "gold", cursor: "pointer" }}
    >
      赋能id
    </div>
  );
};

const Child2 = () => {
  return (
    <div
      className="class"
      style={{ marginTop: 10, background: "violet", cursor: "pointer" }}
    >
      赋能class
    </div>
  );
};

const CHildHoc = HOC({
  target: "button",
  handler: () => {
    Toast.show("按钮赋能");
  },
})(Child);

const CHildHoc1 = HOC({
  target: "#id",
  handler: () => {
    Toast.show("id赋能");
  },
})(Child1);

const CHildHoc2 = HOC({
  target: ".class",
  handler: () => {
    Toast.show("class赋能");
  },
})(Child2);

const Index: React.FC<any> = (props) => {
  return (
    <div style={{ padding: 20 }}>
      <CHildHoc />
      <CHildHoc1 />
      <CHildHoc2 />
    </div>
  );
};

export default Index;
